package fcc.Seng462project.server;

/* HTTP Servlet to receive an upload from the HTML upload from the client side
  */

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.blobstore.BlobInfo;
import com.google.appengine.api.blobstore.BlobInfoFactory;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;
import fcc.Seng462project.client.entities.FileInfo;

//The FormPanel must submit to a servlet that extends HttpServlet  
//RemoteServiceServlet cannot be used because of how GWT works
@SuppressWarnings("serial")
public class UploadServiceImpl extends HttpServlet {

  //Start Blobstore & Objectify Sessions
  BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
  Objectify ofy = ObjectifyService.begin();

  //remember the upload URL created by BlobServiceImpl? This is where the URL points to and is processed server side
  public void doPost(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {
	@SuppressWarnings("deprecation") //Fuck your deprecation Google
	Map<String, BlobKey> blobs = blobstoreService.getUploadedBlobs(req);
    BlobKey blobKey = blobs.get("upload");
    BlobInfo theBlob = new BlobInfoFactory().loadBlobInfo(blobKey);
    
    //Get the parameters from the request to populate the FileInfo object
    FileInfo file = new FileInfo();
    file.setName(theBlob.getFilename());
    file.setOwner(req.getParameter("fileOwner"));   //get the parameter from the form
    file.setSize(theBlob.getSize());
    file.setFileType(theBlob.getContentType());
    file.setBlobkey(blobKey.getKeyString());
    //Map the FileURL to the blobservice servlet, which will serve the file
    file.setFileUrl("/seng462project/blobservice?blob-key=" + blobKey.getKeyString());
    
    //Store the file details in the datastore using objectify
    ofy.put(file);

    //Redirect recursively to this servlet (calls doGet)
    res.sendRedirect("/upload?id=" + file.id);
  }

  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    //Send the meta-data id back to the client in the HttpServletResponse response
    String id = req.getParameter("id");
    resp.setHeader("Content-Type", "text/html");
    resp.getWriter().println(id);

  }

}